//定义全局变量
var orDel = false;
var token = selectByKey("like_token");
var mask = document.querySelector(".mask");
var imgname = document.querySelector("footer img").src.split('/');
imgname.pop();
var dirpath = imgname.join("/");
dirpath += "/";
var src = dirpath;
var opaNum;
//ajax模板
function jshtml(data, scriptdom) {
    var mainmax = document.getElementById('trolley');
    var html = mainmax.innerHTML;
    for (var k in data) {
        var htmlm = scriptdom.innerHTML;
        htmlm = htmlm.replace(/\{\{imgsrc\}\}/, data[k].img);
        htmlm = htmlm.replace(/\{\{num\}\}/, data[k].shop_total);
        htmlm = htmlm.replace(/\{\{h3\}\}/g, data[k].goodname);
        htmlm = htmlm.replace(/\{\{price\}\}/, data[k].price);
        htmlm = htmlm.replace(/\{\{price\}\}/, (data[k].price*data[k].shop_total).toFixed(2));
        htmlm = htmlm.replace(/\{\{id\}\}/, data[k].shop_id);
        htmlm = htmlm.replace(/\{\{shop_type\}\}/, data[k].shop_type);
        htmlm = htmlm.replace(/\{\{cartid\}\}/, data[k].cart_id);
        htmlm = htmlm.replace(/\{\{module\}\}/, data[k].module);
        htmlm = htmlm.replace(/\{\{seller\}\}/, data[k].seller);
        html += htmlm;
    }
    mainmax.innerHTML = html;
}
//END
//显示提示信息
function infoMsg(message) {
    var info = document.querySelector(".info");
    info.style.display = "block";
    var infoCon = info.querySelector("p");
    if(message){
        infoCon.innerHTML = message;
    }
    info.style.opacity = 1;
    setTimeout(function(){
        info.style.opacity = 0;
    },1000);
    setTimeout(function(){
        info.style.display = "none";
    },1500)
}
//重新登录
function reEnter () {
    var info = document.querySelector(".info");
    info.style.display = "block";
    var infoCon = info.querySelector("p");
    infoCon.innerHTML = '登录状态已过期，请重新登录';
    info.style.opacity = 1;
    setTimeout(function(){
        window.location.href = 'personal/enter.html';
    },1000);
}
//加减数量和计算价格模块
function allm() {
    var trolley = document.getElementById('trolley');
    var is = trolley.querySelectorAll('i');
    var ss = trolley.querySelectorAll('s');
    var inputs = trolley.querySelectorAll('.input');
    var checks = trolley.querySelectorAll('.check');
    var aftNum = document.querySelector("header label");
    //点击-
    for (var i = 0; i < is.length; i++) {
        Tap(is[i], function (e, dom) {
            e.preventDefault();
            var goodId = dom.parentNode.getAttribute("data-shopid");
            var cartId = dom.parentNode.getAttribute("data-cartid");
            var unitPrice = dom.parentNode.getAttribute("data-price");
            var val = dom.nextElementSibling.innerHTML;
            var preVal = val;
            val--;
            if(val<=1){
                val = 1;
                dom.style.color = 'lightgray';
            }
            dom.parentNode.lastChild.previousSibling.children[1].innerHTML = val * unitPrice;
            dom.nextElementSibling.innerHTML = val;
            if(dom.parentNode.children[0].children[0].src == dirpath + "iconfont-gou.png"){
                if(preVal > 1){
                    //ajax更改购物车数量
                    mask.style.display = "block";
                    $.ajax({
                        url:pathName+"/api/v1/member/cart/"+cartId+"/update",
                        type:"POST",
                        headers:{
                            "Accept":"application/json",
                            "Authorization":"Bearer "+token
                        },
                        data:{
                            "good_id":goodId,
                            "good_num":val
                        },
                        success:function(value){
                        	console.log(value)
                            if(value.total){
                                mask.style.display = "none";
                                $("#finalprice").text(value.total);
                                dom.parentNode.lastChild.previousSibling.children[1].innerHTML = (value.price*val).toFixed(2);
                                aftNum.innerHTML = "购物车("+value.cartNum+")";
                            }
                        },
                        error:function() {
                            if(!token){
                                reEnter();
                            }
                        }
                    })
                }
            }

        })
    }
    //点击+
    for (var s = 0; s < ss.length; s++) {
        Tap(ss[s], function (e, dom) {
            var shopType = dom.parentNode.getAttribute("data-shop_type");
            if(shopType == 1 && dom.previousElementSibling.innerHTML >= 20){
                infoMsg();
                return;
            }else{
                dom.previousElementSibling.innerHTML++;
                if(dom.previousElementSibling.innerHTML>1){
                    dom.previousSibling.previousSibling.style.color = '';
                }
                if(dom.parentNode.children[0].children[0].src == dirpath+'Oval.png'){
                    dom.parentNode.children[0].children[0].src = dirpath+'iconfont-gou.png';
                    orAll();
                    cal();
                }
                //ajax2更改购物车数量
                var goodId = dom.parentNode.getAttribute("data-shopid");
                var cartId = dom.parentNode.getAttribute("data-cartid");
                mask.style.display = "block";
                $.ajax({
                    url:pathName+"/api/v1/member/cart/"+cartId+"/update",
                    type:"POST",
                    headers:{
                        "Accept":"application/json",
                        "Authorization":"Bearer "+token
                    },
                    data:{
                        "good_id":goodId,
                        "good_num":dom.previousElementSibling.innerHTML
                    },
                    success:function(value){
                    	console.log(value)
                        if(value.total){
                            mask.style.display = "none";
                            $("#finalprice").text(value.total);
                            aftNum.innerHTML = "购物车("+value.cartNum+")";
                            dom.parentNode.lastChild.previousSibling.children[1].innerHTML = (value.price*dom.previousElementSibling.innerHTML).toFixed(2);
                        }
                    },
                    error:function(){
                        if(!token){
                            reEnter();
                        }
                    }
                })
            }
        })
    }
    //进入页面减号颜色的判断
    function adjColor(){
        for(var j = 0; j < inputs.length; j++){
            if(inputs[j].value <= 1){
                inputs[j].previousSibling.style.color = 'lightgray';
            }else{
                inputs[j].previousSibling.style.color = '';
            }
        }
    }
    adjColor();
    //点击输入框
    var mark = document.getElementsByClassName("mark")[0];
    var jian = mark.querySelector("i");
    var jia = mark.querySelector("s");
    var num = 0,customaryNum=0;
    for(var m = 0; m < inputs.length; m++){
        inputs[m].index = m;
        Tap(inputs[m],function(e,dom){
            e.preventDefault();
            var  inp = mark.querySelector("input");
            num = dom.index;
            inp.value = dom.innerHTML;
            customaryNum=dom.innerHTML;
            mark.style.display = "block";
            if(inp.value>1){
                jian.style.color = "";
            }else{
                jian.style.color = "lightgray";
            }
            inp.focus();
        });
    }
    //点击弹出框的+
    Tap(jia,function(e,dom){
        dom.previousElementSibling.value++;
        if(dom.previousElementSibling.value>1){
            dom.previousSibling.previousSibling.style.color = '';
        }
    });

    //点击弹出框的-
    Tap(jian,function(e,dom){
        var val = dom.nextElementSibling.value;
        val--;
        if(val<=1){
            val = 1;
            dom.style.color = 'lightgray';
        }
        dom.nextElementSibling.value = val;
    });
    //点击输入框中的确定
    var sure = mark.querySelector("#sure");
    var cancel = mark.querySelector("#cancle");
    Tap(sure,function(){
        var inp = mark.querySelector("input");
        var val =inp.value;
        if(val<1){
            val = 1;
        }
        if(val == 1){
            inputs[num].previousSibling.style.color = 'lightgray';
        }
        var goodId = inputs[num].parentNode.getAttribute("data-shopid");
        var cartId = inputs[num].parentNode.getAttribute("data-cartid");
        var shopType = inputs[num].parentNode.getAttribute("data-shop_type");
        mark.style.display = 'none';
        adjColor();
        mask.style.display = "block";
        if(shopType == 1 && val > 20){
            inputs[num].innerHTML = 20;
            infoMsg("特价花限购20扎");
            $.ajax({
                url:pathName+"/api/v1/member/cart/"+cartId+"/update",
                type:"POST",
                headers:{
                    "Accept":"application/json",
                    "Authorization":"Bearer "+token
                },
                data:{
                    "good_id":goodId,
                    "good_num":20
                },
                success:function(value){
                    mask.style.display = "none";
                    $("#finalprice").text(value.total);
                    aftNum.innerHTML = "购物车("+value.cartNum+")";
                    inputs[num].parentNode.lastChild.previousSibling.children[1].innerHTML = (value.price*20).toFixed(2);
                },
                error:function(){
                    if(!token){
                        reEnter();
                    }
                }
            })
        }else{
            inputs[num].innerHTML = val;
            //ajax3更改购物车数量
            $.ajax({
                url:pathName+"/api/v1/member/cart/"+cartId+"/update",
                type:"POST",
                headers:{
                    "Accept":"application/json",
                    "Authorization":"Bearer "+token
                },
                data:{
                    "good_id":goodId,
                    "good_num":val
                },
                success:function(value){
                	console.log(value)
                	if (value.code==-1) {
                		mask.style.display = "none";
                		alert("库存不足");
                		inputs[num].innerHTML=customaryNum;
                	} else{
                		mask.style.display = "none";
                    $("#finalprice").text(value.total);
                    aftNum.innerHTML = "购物车("+value.cartNum+")";
                    inputs[num].parentNode.lastChild.previousSibling.children[1].innerHTML = (value.price*val).toFixed(2);
                	}
                    
                },
                error:function(){
                    if(!token){
                        reEnter();
                    }
                }
            })
        }

    });
    //点击取消
    Tap(cancel,function(){
        mark.style.display = 'none';
    });
    var fdiv = trolley.querySelectorAll('.ddd');
    var finalprice = document.getElementById('finalprice');
    //点击选中
    for (var c = 0; c < checks.length; c++) {
        inputs[c].onblur = function () {
            if (this.value <= 0) {
                this.value = 0;
            }
        };
        Tap(checks[c], function (e, dom) {
            var imgname = dom.children[0].src.split('/')[dom.children[0].src.split('/').length - 1];
            if (imgname == 'iconfont-gou.png') {
                dom.children[0].src = dirpath + 'Oval.png';
                if(!orDel){
                    dom.children[0].setAttribute('c', 0);
                }
            } else {
                dom.children[0].src = dirpath + 'iconfont-gou.png';
                if(!orDel){
                    dom.children[0].setAttribute('c', 1);
                }
                //ajax 4
            }
            orAll();
            cal();
        });
    }
    //计算总价
    function cal(){
        var totlePrice = 0;
        for(var i = 0; i < checks.length; i++){
            if(checks[i].children[0].src==(dirpath + 'iconfont-gou.png') || checks[i].children[0].src==(src + 'iconfont-gou.png')){
                m++;
                totlePrice += parseFloat(checks[i].parentNode.getAttribute("data-price")*(checks[i].parentNode.children[4].innerHTML));
            }
        }
        totlePrice = totlePrice.toFixed(2);
        var totle = document.querySelector("#finalprice");
        if(totle){
            totle.innerHTML = totlePrice;
        }
    }
    var qxuan = document.querySelector('footer .check');
    //点击输入框END
    //是否全选
    function orAll() {
        var m = 0;
        var number = 0;
        for(var i = 0; i < checks.length; i++){
            if(checks[i].children[0].src==(dirpath + 'iconfont-gou.png') || checks[i].children[0].src==(src + 'iconfont-gou.png')){
                m++;
                number += parseInt(checks[i].parentNode.children[4].innerHTML);
            }
        }
        $("header label").text("购物车("+number+")");
        if(m == checks.length){
            document.querySelector("footer .check").children[0].src = dirpath + 'iconfont-gou.png';
        }else{
            document.querySelector("footer .check").children[0].src = dirpath + 'Oval.png';
        }
        var em = document.querySelector('footer em');
        if(m>0 && orDel == true){
            em.style.color = "white";
            em.style.border = 0;
            em.style.background = "black";
        }else{
            em.style.color = "";
            em.style.border = "";
            em.style.background = "";
        }
    }
    //点击全选
    Tap(qxuan, function (e, dom) {
        var imgname = dom.children[0].src.split('/')[dom.children[0].src.split('/').length - 1];
        //console.log(imgname);
        var em = document.querySelector("footer em");
        dom.children[0].src = src + 'iconfont-gou.png';
        if (imgname == 'iconfont-gou.png') {
            dom.children[0].src = src + 'Oval.png';
            for (var f = 0; f < fdiv.length; f++) {
                fdiv[f].querySelector('.check').children[0].src = src + 'Oval.png';
                if(orDel == false){
                    fdiv[f].querySelector('.check').children[0].setAttribute('c', 0);
                }
            }
            if(document.querySelector("footer em")){
                em.style.color = "";
                em.style.border = "";
                em.style.background = "";
            }
            finalprice.innerHTML = 0;
        } else {
            dom.children[0].src = src + 'iconfont-gou.png';
            for (var k = 0; k < fdiv.length; k++) {
                fdiv[k].querySelector('.check').children[0].src = src + 'iconfont-gou.png';
                if(orDel == false){
                    fdiv[k].querySelector('.check').children[0].setAttribute('c', 1);
                }
            }
            if(document.querySelector("footer em")){
                em.style.color = "white";
                em.style.border = 0;
                em.style.background = "black";
            }
            //ajax 5
            cal();
        }
    });
    del();
}
//删除购物车商品模块
function del() {
    var edit = document.querySelector("header span");
    var foot = document.querySelector("footer");
    var em = document.querySelector(" footer em");
    var kong = document.querySelector("#trolley .kong");
    Tap(edit,function(e,dom){
        var checks = document.querySelectorAll(".check");
        if(dom.innerHTML == "编辑"){
            orDel = true;
            dom.style.opacity = 0;
            setTimeout(function(){
                dom.innerHTML = "取消";
                dom.style.opacity = 1;
            },200);
            em.style.color = "";
            em.style.border = "";
            em.style.background = "";
            //改变节点
            var childern = foot.children.length;
            for(var i = childern-1; i >= 2; i--){
                foot.children[i].style.display = "none";
            }
            em.style.display = "block";
            //改变选中状态
            for(var m = 0; m < checks.length; m++){
                //console.log(checks[m])
                checks[m].children[0].src = dirpath + "Oval.png";
            }
            document.querySelector("footer .check").children[0].src = dirpath + "Oval.png";
        }else{
            orDel = false;
            console.log(checks);
            dom.style.opacity = 0;
            setTimeout(function(){
                dom.innerHTML = "编辑";
                dom.style.opacity = 1;
            },500);
            em.style.display = "none";
            for(var o = 3; o < foot.children.length; o++){
                foot.children[o].style.display = "block";
            }
            var v = 0;
            var totlePrice = 0;
            for(var n = 0; n < checks.length-1; n++){
                var c = checks[n].children[0].getAttribute("c");
                if(c == 0){
                    checks[n].children[0].src = dirpath + "Oval.png";
                }else{
                    checks[n].children[0].src = dirpath + "iconfont-gou.png";
                    v++;
                    totlePrice += parseFloat(checks[n].parentNode.getAttribute("data-price")*(checks[n].parentNode.children[4].innerHTML));
                }
            }
            totlePrice = totlePrice.toFixed(2);
            console.log(totlePrice);
            var totle = document.querySelector("#finalprice");
            if(totle){
                totle.innerHTML = totlePrice;
            }
            if(v == checks.length-1){
                document.querySelector("footer .check").children[0].src = dirpath + "iconfont-gou.png";
            }else{
                document.querySelector("footer .check").children[0].src = dirpath + "Oval.png";
            }

        }
    });
    //点击删除
    var markT = document.querySelector(".markT");
    var carIdArr = [];
    Tap(em,function(e,dom){
        carIdArr = [];
        var checks = document.querySelectorAll(".check");
        if(dom.style.color == "white"){
            var emV = markT.querySelector("em");
            var kl = 0;
            for(var i = 0; i < checks.length-1; i++){
                if(checks[i].children[0].src == dirpath + "iconfont-gou.png"){
                    kl = kl +1;
                }
            }
            emV.innerHTML = kl;
            markT.style.display = 'block';
        }
    });
    //点击确定与取消
    var sureT = document.getElementById("sureT");
    var cancleT = document.getElementById("cancleT");
    Tap(sureT,function(){
        var checks = document.querySelectorAll(".check");
        for(var j = 0; j < checks.length-1; j++){
            if(checks[j].children[0].src == dirpath + "iconfont-gou.png"){
                var id = checks[j].parentNode.getAttribute("data-cartid");
                carIdArr.push(id);
            }
        }
        //ajax6
        $.ajax({
            url:pathName+"/api/v1/member/cart/delete",
            type:"POST",
            dataType:"json",
            headers:{
                "Accept":"application/json",
                "Authorization":"Bearer "+token
            },
            data:{
                "cartIds":carIdArr
            },
            success:function(data){
                console.log(data);
                carIdArr = [];
                var checks = document.querySelectorAll(".check");
                for(var i = 0; i < checks.length-1; i++){
                    if(checks[i].children[0].src == dirpath+ "iconfont-gou.png"){
                        checks[i].parentNode.parentNode.removeChild(checks[i].parentNode)
                    }
                }
                $("header label").text("购物车("+data.countCart+")");
                var finalPrice = document.querySelector("footer label");
                finalPrice.innerHTML = data.total;
                if($(".check").length == 1){
                    $("footer .check img").attr("src",dirpath + "Oval.png");
                }
                em.style.color = "";
                em.style.border = "";
                em.style.background = "";
                markT.style.display = 'none';
                if(data.countCart == 0){
                    foot.style.display = "none";
                    edit.style.display = "none";
                    kong.style.display = "block";
                }
            },
            error:function(){
                if(!token){
                    reEnter();
                }
            }
        });
    });
    Tap(cancleT,function(){
        markT.style.display = 'none';
    });
}
//点击结算，提交订单模块
function submit(){
    var finalPrice = document.getElementById("finalprice").innerHTML;
    var submit = document.getElementById("submit");
    Tap(submit,function(){
        if(finalPrice>0){
            var goods = [];
            var cartIds = [];
            var checks = document.querySelectorAll(".check");
            for(var i = 0; i < checks.length-1; i++){
                var obj = {};
                if(checks[i].children[0].src == dirpath + "iconfont-gou.png" || checks[i].children[0].src == src + "iconfont-gou.png"){
                    var ids = checks[i].parentNode.getAttribute("data-shopid");
                    var module = checks[i].parentNode.getAttribute("data-module");
                    var seller = checks[i].parentNode.getAttribute("data-seller");
                    var nums = checks[i].parentNode.children[4].innerHTML;
                    obj.good_id = ids;
                    obj.good_num = nums;
                    obj.good_type = checks[i].parentNode.getAttribute("data-shop_type");
                    obj.module=module;
                    obj.seller=seller;
                    var cartId = checks[i].parentNode.getAttribute("data-cartid");
                    cartIds.push(cartId);
                }
                goods.push(obj);
            }
            console.log(cartIds)
            var str = JSON.stringify(goods);
            localStorage.setItem("str",str);
            console.log(token);
            $.ajax({
                url:pathName+"/api/v1/member/cart/"+cartIds[0]+"/order/result",
                type:"POST",
                dataType:"json",
                headers:{
                    "Accept":"application/json",
                    "Authorization":"Bearer "+token
                },
                data:{
                    "cartIds":cartIds
                },
                success:function(data){
                    console.log(data);
                    var cartIdsStr = JSON.stringify(cartIds);
                    localStorage.setItem("cartIds",cartIdsStr);
                    localStorage.setItem("orderId",data.order_id);
                    var num = Math.floor(Math.random()*8999 + 9999);
                    window.location.href = "allorder/torders.html?t=201703" + num;
                },
                error:function(){
                    if(!token){
                        reEnter();
                    }
                }
            })
        }else{

        }
    });

}
//END
window.onload = function () {
    var kong = document.querySelector("#trolley .kong");
    var edit = document.querySelector("header span");
    var foot = document.querySelector("footer");
    kong.style.display = "none";
    //首次加载购物车中内容
    console.log(token);
    $.ajax({
        url:pathName+"/api/v1/member/cart",
        type:"get",
        headers:{
            "Accept":"application/json",
            "Authorization":"Bearer "+token
        },
        success:function(value){
            console.log(value);
            mask.style.display = "none";
            if(value.count>0){
                kong.style.display = "none";
                var count = value.count;
                var total_cost = value.total_cost;
                $("header label").text("购物车("+count+")");
                $("#finalprice").text(total_cost);
                var carts = value.carts;
                var mode = document.getElementById("mode");
                jshtml(carts,mode);
                allm();
                submit();
            }else{
                kong.style.display = "block";
                edit.style.display = "none";
                foot.style.display = "none";
            }

        },
        error:function (){
            if(!token){
                reEnter();
            }
        }
    });
    
    
    
    
    
    
};